package com.hxzy.service.system.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxzy.dto.system.DeptSearchDTO;
import com.hxzy.entity.system.SysDept;
import com.hxzy.mapper.system.SysDeptMapper;
import com.hxzy.service.system.SysDeptService;
import com.hxzy.vo.system.SysDeptTreeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    public List<SysDept> selectSysDeptList(SysDept sysDept) {
        return sysDeptMapper.selectSysDeptList(sysDept);
    }

    @Override
    public List<SysDeptTreeVO> buildTreeVo(DeptSearchDTO deptSearchDTO) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(deptSearchDTO.getDeptName())){
            queryWrapper.like(SysDept::getDeptName,deptSearchDTO.getDeptName());
        }
        if (StrUtil.isNotBlank(deptSearchDTO.getStatus())){
            queryWrapper.like(SysDept::getStatus,deptSearchDTO.getStatus());
        }
        queryWrapper.orderBy(true,true,SysDept::getParentId,SysDept::getOrderNum);
        //查询到数据
        List<SysDept> all = this.list(queryWrapper);

        return buildDeptTree(all);
    }

    private List<SysDeptTreeVO> buildDeptTree(List<SysDept> all) {

        List<SysDeptTreeVO>   treeVOList=new ArrayList<>();
        // 加入所有查询出来的(防止后面程序多次加载数据用)
        List<Long> tempIds=new ArrayList<>();
        all.forEach(p-> {
            tempIds.add(p.getId());
        });

        //查询
        for(SysDept  dept: all) {
            if(!tempIds.contains(dept.getParentId())){
                //查询不到就是顶级节点, 遍历该父节点的所有子节点
                SysDeptTreeVO root = new SysDeptTreeVO();
                BeanUtils.copyProperties(dept, root);
                //查询它的下一级
                recursionFn(all, root);
                treeVOList.add(root);
            }
        }
        return  treeVOList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> all,SysDeptTreeVO root) {
        List<SysDeptTreeVO> childList = new ArrayList<>();

        all.stream().filter(p-> p.getParentId().longValue()==root.getId().longValue()).forEach(p -> {
            SysDeptTreeVO child = new SysDeptTreeVO();
            BeanUtils.copyProperties(p,child);
            //递归下一级
            recursionFn(all,child);
            childList.add(child);
        });
        //遍历子节点下面的子节点
        if(childList.size()>0){
            root.setChildren(childList);
        }
    }
}
